const swaggerJSDoc = require('swagger-jsdoc');
const path = require('path');
const express = require('express');
const router = express.Router();
const ai = require('../controllers/questionSourceController.js');

// 优化Swagger JSON输出的函数
function optimizeForAI(swaggerSpec) {
  return {
    info: swaggerSpec.info,
    servers: swaggerSpec.servers,
    paths: Object.entries(swaggerSpec.paths).reduce((acc, [path, methods]) => {
      acc[path] = Object.entries(methods).reduce((methodAcc, [method, def]) => {
        methodAcc[method] = {
          summary: def.summary,
          description: def.description,
          parameters: def.parameters,
          requestBody: def.requestBody,
          responses: def.responses,
          // 添加AI辅助字段
          aiTips: {
            commonErrors: def.responses ? Object.keys(def.responses)
              .filter(code => code >= '400')
              .map(code => ({
                code,
                description: def.responses[code].description
              })) : [],
            sampleRequest: def.requestBody ? {
              contentType: Object.keys(def.requestBody.content)[0],
              schema: def.requestBody.content[Object.keys(def.requestBody.content)[0]].schema
            } : null
          }
        };
        return methodAcc;
      }, {});
      return acc;
    }, {}),
    components: {
      schemas: swaggerSpec.components.schemas
    }
  };
}

const options = {
    definition: {
        openapi: '3.0.0',
        info: {
            title: 'API 文档',
            version: '1.0.0',
            description: 'API 文档描述',
        },
        servers: [
            {
                "url": "http://localhost:3000",
                description: 'API 服务器',
            },
        ],
        components: {
            schemas: {
                QuestionSource: {
                    type: 'object',
                    required: ['sourceType', 'sourceContent'],
                    properties: {
                        sourceType: {
                            type: 'string',
                            description: '题目来源类型'
                        },
                        sourceContent: {
                            type: 'string',
                            description: '题目来源内容'
                        },
                        id: {
                            type: 'string',
                            description: '文档ID'
                        },
                        createdAt: {
                            type: 'string',
                            format: 'date-time',
                            description: '创建时间'
                        },
                        updatedAt: {
                            type: 'string',
                            format: 'date-time',
                            description: '更新时间'
                        }
                    }
                },
                KnowledgeNode: {
                    type: 'object',
                    required: ['title'],
                    properties: {
                        title: {
                            type: 'string',
                            description: '节点标题'
                        },
                        content: {
                            type: 'string',
                            description: '节点内容'
                        },
                        parentId: {
                            type: 'string',
                            description: '父节点ID'
                        },
                        order: {
                            type: 'number',
                            description: '同级节点排序'
                        },
                        level: {
                            type: 'number',
                            description: '节点层级'
                        },
                        createdBy: {
                            type: 'string',
                            description: '创建者ID'
                        },
                        id: {
                            type: 'string',
                            description: '文档ID'
                        },
                        createdAt: {
                            type: 'string',
                            format: 'date-time',
                            description: '创建时间'
                        },
                        updatedAt: {
                            type: 'string',
                            format: 'date-time',
                            description: '更新时间'
                        }
                    }
                },
                Question: {
                    type: 'object',
                    required: ['type', 'points', 'difficulty', 'source'],
                    properties: {
                        content: {
                            type: 'string',
                            description: '题目文本内容'
                        },
                        htmlContent: {
                            type: 'string',
                            description: '题目富文本内容(HTML)'
                        },
                        image: {
                            type: 'string',
                            description: '题目图片路径/URL'
                        },
                        type: {
                            type: 'string',
                            description: '题目类型ID'
                        },
                        options: {
                            type: 'array',
                            items: {
                                type: 'object',
                                properties: {
                                    label: {
                                        type: 'string',
                                        description: '选项标签(A-Z)'
                                    },
                                    content: {
                                        type: 'string',
                                        description: '选项文本内容'
                                    },
                                    htmlContent: {
                                        type: 'string',
                                        description: '选项富文本内容(HTML)'
                                    },
                                    image: {
                                        type: 'string',
                                        description: '选项图片路径/URL'
                                    },
                                    isCorrect: {
                                        type: 'boolean',
                                        description: '是否为正确答案'
                                    }
                                }
                            },
                            description: '题目选项'
                        },
                        answer: {
                            type: 'array',
                            items: {
                                type: 'string'
                            },
                            description: '题目答案(文本)'
                        },
                        htmlAnswer: {
                            type: 'string',
                            description: '题目答案(富文本HTML)'
                        },
                        imageAnswer: {
                            type: 'string',
                            description: '题目答案(图片路径/URL)'
                        },
                        points: {
                            type: 'number',
                            description: '题目分值'
                        },
                        difficulty: {
                            type: 'number',
                            description: '难度级别(1-5)'
                        },
                        tags: {
                            type: 'array',
                            items: {
                                type: 'string'
                            },
                            description: '知识点标签'
                        },
                        source: {
                            type: 'string',
                            description: '题目来源'
                        },
                        id: {
                            type: 'string',
                            description: '文档ID'
                        },
                        createdAt: {
                            type: 'string',
                            format: 'date-time',
                            description: '创建时间'
                        },
                        updatedAt: {
                            type: 'string',
                            format: 'date-time',
                            description: '更新时间'
                        }
                    }
                },
                QuestionType: {
                    type: 'object',
                    required: ['name'],
                    properties: {
                        name: {
                            type: 'string',
                            description: '题目类型名称'
                        },
                        createdAt: {
                            type: 'string',
                            format: 'date-time',
                            description: '创建时间'
                        },
                        updatedAt: {
                            type: 'string',
                            format: 'date-time',
                            description: '创建时间'
                        },
                        id: {
                            type: 'string',
                            description: '文档ID,由虚拟属性自动生成'
                        },
                    }
                },
                User: {
                    type: 'object',
                    required: ['username', 'email', 'password'],
                    properties: {
                        username: {
                            type: 'string',
                            description: '用户名'
                        },
                        email: {
                            type: 'string',
                            description: '电子邮件'
                        },
                        password: {
                            type: 'string',
                            description: '密码(哈希后)'
                        },
                        role: {
                            type: 'string',
                            enum: ['student', 'teacher', 'admin'],
                            description: '用户角色'
                        },
                        isActive: {
                            type: 'boolean',
                            description: '是否激活'
                        },
                        profile: {
                            type: 'object',
                            properties: {
                                name: {
                                    type: 'string',
                                    description: '用户姓名'
                                },
                                avatar: {
                                    type: 'string',
                                    description: '头像URL'
                                },
                                bio: {
                                    type: 'string',
                                    description: '个人简介'
                                }
                            },
                            description: '用户资料'
                        },
                        id: {
                            type: 'string',
                            description: '文档ID'
                        },
                        createdAt: {
                            type: 'string',
                            format: 'date-time',
                            description: '创建时间'
                        },
                        updatedAt: {
                            type: 'string',
                            format: 'date-time',
                            description: '更新时间'
                        }
                    }
                }
            }
        }
    },
    apis: [path.resolve(__dirname, '../controllers/*.js')], // 包含注释的文件路径
};

const swaggerSpec = swaggerJSDoc(options);

// 设置路由
router.get('/json', (req, res) => {
  res.json(optimizeForAI(swaggerSpec));
});

router.use('/', require('swagger-ui-express').serve);
router.get('/', require('swagger-ui-express').setup(swaggerSpec));

module.exports = router;
//console.log(JSON.stringify(swaggerSpec, null, 2));
